<template>
	<view class="container">
		<u-navbar leftText="优惠券列表" @leftClick="appFinish" leftIconColor="#1D2129" bgColor="transparent">
		</u-navbar>
		<view class="content">
			<view class="top_search">
				<u-search :showAction="true" actionText="确认" v-model.trim="params.name" :animation="true"
					placeholder="请输入优惠券名称" borderColor="#979797" bgColor="#ffffff" @clear="search"
					@custom="search"></u-search>
			</view>
			<u-tabs class="custom_tab" :list="tabs" lineColor="#295EFF" :activeStyle="activeStyle"
				:inactiveStyle="inactiveStyle" :current="currentTab" :itemStyle="itemStyle" :scrollable="false"
				@change="changeTab">
			</u-tabs>
			<scroll-view @scrolltolower="scrolltolower" scroll-y scroll-with-animation class="content_scroll_view">
				<view class="item_list" v-for="(item, index) in couponList" :key="index">
					<view class="item_top">
						<view :class="['item_status', getStatusClass(item.type)]">{{ getStatusText(item.type) }}</view>
						<view class="item_title ex">{{ item.name }}</view>
					</view>
					<view class="item_bottom">
						<view class="item">
							<view class="item_left">
								<view class="left_top">
									<text v-if="item.type !== 2">￥</text>
									{{ getPoster(item) }}
									<text v-if="item.type == 2">折</text>
								</view>
								<view class="left_bottom ex">{{ item.reductionStr }}</view>
							</view>
							<view class="item_right">
								<view class="item_condition ex">{{ item.timeRangeStr }}</view>
								<view class="item_condition ex">{{ getProductType(item.targetProductType) }}</view>
								<view class="item_condition ex">已领取：{{ item.recvedNum }}张｜已使用：{{ item.usedNum }}张｜剩余：{{
									item.total - item.recvedNum - item.frozenNum }}张</view>
							</view>
						</view>
						<view class="item_btn">
							<view v-if="[1,2].includes(params.status)" @click="currentItem(item)">更多</view>
							<view v-else></view>
							<view class="right_btn">
								<view v-if="item.canEdit" @click="goToAddCoupon('isEdit', item.couponId)">编辑</view>
								<view v-if="params.status === 4 || params.status === 3" class="margin_left" @click="goToAddCoupon('isCopy')">复制</view>
								<view v-if="item.status !== 4 && params.status === 3" class="primary_btn" @click="handleInvalid(item)">失效</view>
								<view v-if="item.canActivate" class="primary_btn" @click="handleActivate(item)">开启</view>
								<view v-if="item.canShare" class="primary_btn" @click="handleShare(item)">分享</view>
								<view v-if="item.canDelete" class="primary_btn" @click="handleDelete(item)">删除</view>
							</view>
						</view>
					</view>
				</view>
				<div class="listSpace" v-if="couponList.length <= 0">
					<list-space></list-space>
				</div>
				<view class="cj_space"></view>
			</scroll-view>
		</view>
		<view class="footer">
			<u-button type="primary" color="#295FFF" shape="circle" @click="goToAddCoupon('new')">添加优惠券</u-button>
		</view>
		<u-popup :show="isShowShare" @close="closeSharePop" mode="bottom" :round="16" closeable>
			<view class="share-container">
				<view class="pop_title">
					分享优惠券
				</view>
				<view class="pop_body">
					<template v-if="!isSetting">
						<view class="pop_item">
							<view class="label">分享方式</view>
							<view class="radio-content">
								<view class="radio-content" v-for="(item, index) in shareTypeList" :key="index"
									@click="changeRadio(index)">
									<view class="radio" :class="radio == index + 1 ? 'radio-default' : ''">
										<view :class="radio == index + 1 ? 'radio-active' : ''"></view>
									</view>
									<text>{{ item.name }}</text>
								</view>
							</view>
						</view>
						<view class="pop_tips">
							<text v-if="radio == 1">针对全部用户分享场景，分享有效期内所有用户可重复领取，直到领取上限</text>
							<text v-if="radio == 2">针对单人用户分享场景，用户可一次性领取设定的发放数量，领取后二维码失效，避免链接肆意转发领取优惠券。</text>
						</view>
						<view class="pop_item">
							<view class="label">发放数量</view>
							<view class="input-container">
								<u--input v-model="shareObj.num" placeholder="请输入" disabledColor="#F5F7F9" type="number"
									:disabled="radio == 2 && !!shareObj.recvLimit" @change="issueChange" min="1"></u--input>
							</view>
							<text class="unit">张</text>
						</view>
						<view class="pop_item" v-if="radio === 1">
							<view class="label">单人限领</view>
							<view class="input-container" v-if="shareObj.recvLimit">
								<u--input v-model="shareObj.limit" placeholder="不限制" disabledColor="#F5F7F9"
									disabled></u--input>
							</view>
							<text class="unit">{{ shareObj.recvLimit ? "张" : "不限" }}</text>
						</view>
						<view class="bottom_btn">
							<view class="btn" @click="confirm">确认</view>
						</view>
					</template>
					<template v-else>
						<view class="pop_tips">
							当前设置：{{ radio == 1 ? '公开分享' : '私密分享' }}｜发放数量：{{ shareObj.num }}张
							<text v-if="radio == 1 && shareObj.recvLimit">｜领取上限：{{ shareObj.limit }} 张</text>
						</view>
						<view class="qrcode">
							<uqrcode ref="qrcode" canvas-id="qrcode" :value="shareUrl" size="118"></uqrcode>
						</view>
						<view class="share_type">
							<view class="share_item" @click="wxShare">
								<img src="@/static/image/wechat_logo.png" />
								<view class="name">微信</view>
							</view>
							<view class="share_item" @click="copyLink">
								<img src="@/static/image/link.png" />
								<view class="name">复制链接</view>
							</view>
							<view class="share_item" @click="savePhoto">
								<img src="@/static/image/image.png" />
								<view class="name">保存图片</view>
							</view>
						</view>
					</template>
				</view>
			</view>
		</u-popup>
		<u-popup :show="isShowMore" round="10" @close="isShowMore = false" mode="bottom">
			<view class="pop-container">
				<view class="avatar-pop-box">
					<view class="pop-item" @click="goToAddCoupon('isCopy')">
						复制
					</view>
					<view v-if="selectedItem.canDeactivate" class="pop-item" @click="handleDeactivate(selectedItem)">
						停止
					</view>
					<view v-if="selectedItem.status !== 4" class="pop-item" @click="handleInvalid(selectedItem)">
						失效
					</view>
				</view>
				<view class="pop-cancel-item" @click="isShowMore = false">
					取消
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import url_config from '@/utils/config.js'
export default {
	data() {
		return {
			currentTab: 0,
			couponId: '',
			shareTypeList: [
				{ name: '公开分享' },
				{ name: '私密分享' },
			],
			radio: 1,
			tabs: [
				{ name: '进行中' },
				{ name: '未开始' },
				{ name: '已停止' },
				{ name: '已失效' }
			],
			isShowMore: false,
			isShowShare: false,
			isSetting: false,
			activeStyle: {
				color: '#464C5B',
				fontSize: '28rpx',
				fontWeight: 500,
			},
			inactiveStyle: {
				color: '#657180',
				fontSize: '28rpx',
				fontWeight: 400,
			},
			itemStyle: 'height: 34px;',
			couponList: [],
			selectedItem: {},
			shareUrl: '',
			shareObj: {
				couponId: null,
				recvLimit: 0,
				remain: 0,
				limit: 1,
				num: 1
			},
			total: 0,
			params: {
				page: 1,
				pageSize: 10,
				name: '',
				status: 2
			},
			shareItem: {},
			shareCode: ''
		}
	},
	onLoad() {
		// this.getList()
	},
	onShow() {
		this.couponList = []
		this.getList()
	},
	onPullDownRefresh() {
		this.params.page = 1
		this.couponList = []
		this.getList()
	},
	methods: {
		appFinish() {
			this.$utils.appFinish(this)
		},
		goBack() {
			uni.navigateBack();
		},
		search() {
			this.params.page = 1
			this.couponList = []
			this.getList()
		},
		changeTab(item) {
			switch (item.name) {
				case '进行中':
					this.params.status = 2
					break
				case '未开始':
					this.params.status = 1
					break
				case '已停止':
					this.params.status = 3
					break
				case '已失效':
					this.params.status = 4
					break
				default:
					break
			}
			this.params.page = 1
			this.couponList = []
			this.getList()
		},
		changeRadio(index) {
			if (this.radio === 2) {  // 选中私密分享
				this.shareObj.num = this.shareObj.recvLimit || 1
			}
			this.radio = index + 1
		},
		checkDetail(date) {
			uni.navigateTo({
				url: '/pages/trafficStatistics/detail?date=' + date
			});
		},
		goToAddCoupon(type, id) {
			let tempId = id ? id : this.couponId
			this.isShowMore = false
			console.log('goToAddCoupon222==============', type, id, this.couponId)
			uni.navigateTo({
				url: '/pages/couponList/addCoupon?type=' + type + '&id=' + tempId
			})
		},
        issueChange(value) {
			if (Number(value) > this.shareObj.remain) {
				this.$nextTick(() => {
				  this.shareObj.num = this.shareObj.remain
				});
			}
			// if (Number(value) < 1) {
			// 	this.$nextTick(() => {
			// 	  this.shareObj.num = 1
			// 	});
			// }
		},
		// 打开更多
		currentItem(item) {
			this.couponId = item.couponId
			this.selectedItem = item
			this.isShowMore = true
		},
		getStatusClass(type) {
			// 根据 type 返回不同的 class
			switch (type) {
				case 1:
					return 'reduction';
				case 2:
					return 'discount';
				case 3:
					return 'randomReduction';
				default:
					return '';
			}
		},
		getStatusText(type) {
			// 根据 type 返回不同的文本
			switch (type) {
				case 1:
					return '满减券';
				case 2:
					return '折扣券';
				case 3:
					return '随机券';
				default:
					return '全部';
			}
		},
		getProductType(type) {
			// 根据 type 返回不同的文本
			switch (type) {
				case 1:
					return '全部商品';
				case 2:
					return '部分商品';
				case 3:
					return '部分商品不可用';
				default:
					return '';
			}
		},
		getPoster(item) {
			if (item.type == 1) {
				return (item.reduction / 100).toFixed(2)
			} else if (item.type == 2) {
				return (item.reduction / 10).toFixed(2)
			} else if (item.type == 3) {
				return `${(Math.min(...item.randomReduction) / 100).toFixed(2)} ~ ${(Math.max(...item.randomReduction) / 100).toFixed(2)}`
			}
		},
		//开启
		handleActivate(item) {
			uni.showModal({
				title: '提示',
				content: '确认开启该优惠券吗？',
				success: async (res) => {
					if (res.confirm) {
						const {
							data
						} = await this.$request(this.$Api.activateCoupon, {
							couponId: item.couponId
						}, "POST")
						if (data.code !== 200) return
						uni.showToast({
							title: '开启成功！',
							icon: 'none'
						})
						this.params.page = 1
						this.couponList = []
						this.getList()
					}
				}
			})
		},
		// 删除
		handleDelete(item) {
			uni.showModal({
				title: '提示',
				content: '确认删除该优惠券吗？',
				success: async (res) => {
					if (res.confirm) {
						const {
							data
						} = await this.$request(this.$Api.deleteCoupon, {
							couponId: item.couponId
						}, "POST")
						if (data.code !== 200) return
						uni.showToast({
							title: '删除成功！',
							icon: 'none'
						})
						this.params.page = 1
						this.couponList = []
						this.getList()
					}
				}
			})
		},
		// 停止
		handleDeactivate(item) {
			this.isShowMore = false
			uni.showModal({
				title: '提示',
				content: '确认停止该优惠券吗？',
				success: async (res) => {
					if (res.confirm) {
						const {
							data
						} = await this.$request(this.$Api.deactivateCoupon, {
							couponId: item.couponId
						}, "POST")
						if (data.code !== 200) return
						uni.showToast({
							title: '停止成功！',
							icon: 'none'
						})
						this.params.page = 1
						this.couponList = []
						this.getList()
					}
				}
			})
		},
		// 失效
		handleInvalid(item) {
			this.isShowMore = false
			uni.showModal({
				title: '提示',
				content: '失效后已领取该优惠劵的用户将无法使用该优惠劵，是否确认失效？',
				success: async (res) => {
					if (res.confirm) {
						const {
							data
						} = await this.$request(this.$Api.invalidCoupon, {
							couponId: item.couponId
						}, "POST")
						if (data.code !== 200) return
						uni.showToast({
							title: '失效成功！',
							icon: 'none'
						})
						this.params.page = 1
						this.couponList = []
						this.getList()
					}
				}
			})
		},
		// 分享
		async handleShare(item) {
			if (item.total - item.recvedNum - item.frozenNum <= 0) {
				return uni.showToast({
					title: '优惠劵剩余数量不足!',
					icon: 'none',
				})
			}
			// 获取优惠券详情
			const params = { couponId: item.couponId }
			const { data } = await this.$request(this.$Api.queryCouponDetail, params, "get")
			const { total, recvedNum, frozenNum, recvLimit:recvLimitData, couponId } = data.data;
			this.shareObj.couponId = couponId
			this.shareObj.remain = total - recvedNum - frozenNum;
			this.shareObj.recvLimit = recvLimitData
			if (!this.shareObj.recvLimit || this.shareObj.recvLimit > this.shareObj.remain) {
				this.shareObj.limit = this.shareObj.remain;
			} else {
				this.shareObj.limit = this.shareObj.recvLimit;
			}
			this.shareObj.num = 1
			this.isShowShare = true
			// 选中分享的优惠券
			this.shareItem = item
		},
		// 滚动到底部加载更多
		scrolltolower(e) {
			if (this.couponList.length < this.total) {
				this.params.page++
				this.getList()
			} else {
				uni.showToast({
					title: '已到底',
					icon: 'none',
				})
			}
		},
		async getList() {
			const { data } = await this.$request(this.$Api.couponList, this.params, "get")
			this.couponList = this.couponList.concat(data.data.list)
			this.total = data.data.total
			uni.stopPullDownRefresh()
		},
		closeSharePop() {
			this.isShowShare = false
			this.radio = 1
			this.isSetting = false
			this.shareUrl = ''
			this.shareCode = ''
			this.shareObj = {
				couponId: null,
				recvLimit: 0,
				remain: 0,
				limit: 1,
				num: 1
			}
			this.params.page = 1
			this.couponList = []
			this.getList()
		},
		async confirm() {
			if (this.isSetting) {
				this.closeSharePop()
				return
			} else {
				if (Number(this.shareObj.num) < 1) {
					return uni.showToast({
						title: '发放数量不能小于1 !',
						icon: 'none',
					})
				}
				const params = {
					couponId: this.shareObj.couponId,
					shareType: this.radio,
					number: Number(this.shareObj.num),
				}
				const { data } = await this.$request(this.$Api.shareCoupon, params, "post")
				let orgId = await this.$utils.getOrgId(this)
				this.shareUrl = `${url_config.h5Api}/org/${orgId}/coupon/receive/${data.data.code}`
				this.isSetting = true;
				this.shareCode = data.data.code // 分享code
			}
		},
		// 微信分享
		wxShare() {
			this.shareItem.shareCode = this.shareCode
			this.shareItem.shareUrl = this.shareUrl
			const jsonData = JSON.stringify(this.shareItem)
			console.log('分享jsonData', jsonData)
			this.$bridge.call('share', [jsonData, (res) => {

			}])
		},
		// 复制链接
		copyLink() {
			if (this.shareUrl) {
				uni.setClipboardData({
					data: this.shareUrl, // 是你要保存的内容
					success: function () {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					}
				})
			} else {
				uni.showToast({
					title: '复制失败！',
					icon: 'none'
				})
			}
		},
		iosSave(jsonData) {
			console.log("ios保存图片",jsonData)
			this.$bridge.call('iosSavePicture', [jsonData, (res) => {

			}])
		},
		// 保存二维码
		savePhoto() {
			// 判断
			let systemInfo = uni.getSystemInfoSync();
			//#ifdef H5
			this.$refs.qrcode.toTempFilePath({
				success: res => {
					console.log('res.tempFilePath1,', res.tempFilePath,)
					const aEle = document.createElement('a');
					aEle.download = 'uQRCode'; // 设置下载的文件名，默认是'下载'
					aEle.href = res.tempFilePath;
					document.body.appendChild(aEle);
					aEle.click();
					aEle.remove(); // 下载之后把创建的元素删除
					if (systemInfo.platform === 'ios') {
						this.iosSave(res.tempFilePath)
					}
				}
			});
			//#endif
			// #ifdef APP-PLUS
			this.$refs.qrcode.toTempFilePath({
				success: res => {
					console.log('res.tempFilePath,', res.tempFilePath,)
					if (systemInfo.platform === 'ios') {
						this.iosSave(res.tempFilePath)
					}
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.hideLoading();
							uni.showToast({
								title: "图片已保存"
							});
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: "图片保存失败"
							});
						}
					});
				}
			});
			// #endif
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	height: 100vh;
	overflow-y: hidden;
	background: url('@/static/image/my_set_bg.png') no-repeat center center;
	background-size: cover;

	::v-deep .u-navbar__content__left__text {
		font-weight: 500;
		font-size: 32rpx;
	}
    
	.content {
		display: flex;
		flex-direction: column;
		margin-top: 96rpx;
		height: calc(100vh - 96rpx);
		box-sizing: border-box;

		.top_search {
			margin: 0 32rpx;
		}

		.custom_tab {
			margin-top: 10rpx;

			::v-deep .u-tabs__wrapper__nav {
				border-bottom: 2rpx solid #E3E8EE;

				.u-tabs__wrapper__nav__line {
					bottom: 0;
				}
			}
		}

		.content_scroll_view {
			height: calc(100vh - 350rpx);
			padding-top: 24rpx;

			.item_list {
				background: #ffffff;
				border-radius: 14rpx;
				margin: 0 32rpx 24rpx 32rpx;
				.margin_left{
					margin-left: 30rpx;
				}
				.item_top {
					display: flex;
					align-items: center;
					padding: 16rpx 24rpx;
					border-bottom: 2rpx solid #D7DDE4;

					.item_status {
						width: 104rpx;
						height: 46rpx;
						line-height: 46rpx;
						text-align: center;
						background: #00C795;
						border-radius: 8rpx;
						font-weight: 400;
						font-size: 24rpx;
						color: #FFFFFF;

						&.randomReduction {
							background: #00C795;
						}

						&.reduction {
							background: #FF5A5F;
						}

						&.discount {
							background: #2B9CFF;
						}
					}

					.item_title {
						font-weight: 500;
						font-size: 28rpx;
						color: #464C5B;
						margin-left: 16rpx;
					}
				}

				.item_bottom {
					box-sizing: border-box;
					padding-bottom: 24rpx;

					.item {
						display: flex;
						align-items: center;
						margin-top: 26rpx;
						padding: 0 24rpx;
						box-sizing: border-box;
						font-size: 20rpx;
						color: #8C8C8C;

						.item_left {
							display: flex;
							align-items: center;
							flex-direction: column;
							width: 230rpx;

							.left_top {
								font-size: 42rpx;
								color: #FF5A5F;
								line-height: 40rpx;
								text-align: center;
								word-break: break-all;

								text {
									font-size: 20rpx;
								}
							}

							.left_bottom {
								word-break: break-all;
								text-align: center;
								width: 220rpx;
							}
						}

						.item_right {
							flex: 1;

							.item_condition {
								line-height: 28rpx;
								margin-bottom: 24rpx;
							}
						}

					}

					.item_btn {
						display: flex;
						align-items: center;
						justify-content: space-between;
						padding: 0 24rpx;
						box-sizing: border-box;
						font-weight: 400;
						font-size: 24rpx;
						color: #295EFF;
						margin-top: 22rpx;

						img {
							width: 28rpx;
							height: 28rpx;
						}

						.right_btn {
							display: flex;
							align-items: center;

							.primary_btn {
								height: 48rpx;
								padding: 0 32rpx;
								border: 2rpx solid #295EFF;
								border-radius: 8rpx;
								color: #295EFF;
								font-size: 24rpx;
								line-height: 48rpx;
								text-align: center;
								border-radius: 46rpx;
								margin-left: 32rpx;
							}
						}
					}
				}
			}

		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 166rpx;
		box-sizing: border-box;
		padding: 20rpx 40rpx 66rpx 40rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(210, 210, 210, 0.5);
		display: flex;
		align-items: center;
	}

	.cj_space {
		width: 100%;
		height: 30rpx;
	}

	.share-container {
		position: relative;
		height: 656rpx;
		box-sizing: border-box;
		padding: 28rpx 26rpx 26rpx 26rpx;

		.pop_title {
			font-weight: 500;
			font-size: 32rpx;
			color: #464C5B;
			text-align: center;
		}

		.pop_body {
			margin-top: 32rpx;

			.pop_item {
				display: flex;
				align-items: center;
				margin-bottom: 32rpx;

				.unit,
				.label {
					font-weight: 400;
					font-size: 28rpx;
					color: #464C5B;
					line-height: 40rpx;
					margin-right: 16rpx;
				}

				.input-container {
					width: 182rpx;
					margin-right: 16rpx;
				}

				.u-radio {
					margin-left: 55rpx;
				}
			}

			.pop_tips {
				padding: 16rpx;
				background: #F6F9FF;
				border-radius: 8rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #657180;
				margin-bottom: 32rpx;
			}

			.qrcode {
				width: 100%;
				height: 118px;
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 32rpx 0 24rpx 0;

				::v-deep .uqrcode-canvas-wrapper {
					height: 118px;
				}
			}

			.share_type {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.share_item {
					flex: 1;
					text-align: center;
					margin: 24rpx 0 38rpx 0;

					img {
						width: 56rpx;
						height: 56rpx;
					}

					.name {
						font-size: 24rpx;
						color: #657180;
						line-height: 34rpx;
					}
				}
			}

			.radio-content {
				height: 40rpx;
				display: flex;
				align-items: center;

				.radio {
					width: 32rpx;
					height: 32rpx;
					border-radius: 50%;
					border: 2rpx solid #D9D9D9;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					margin: 0 16rpx 0 66rpx;
				}

				.radio-active {
					width: 20rpx;
					height: 20rpx;
					border-radius: 50%;
					background: #0975E0;
				}

				.radio-default {
					border: 2rpx solid #0975E0;
				}

				.radio-right {
					margin-left: 66rpx;
				}

				text {
					font-size: 28rpx;
				}
			}

			.bottom_btn {
				position: fixed;
				left: 0;
				bottom: 0;
				width: 100%;
				text-align: center;
				box-sizing: border-box;
				padding: 20rpx 78rpx 52rpx 78rpx;

				.btn {
					font-size: 32rpx;
					color: #FFFFFF;
					padding: 20rpx 0;
					background: #295FFF;
					border-radius: 46rpx;
				}
			}
		}
	}

	.pop-container {
		font-size: 34rpx;
		color: #000000;
		text-align: center;
		background-color: #ffffff;
		border-radius: 24rpx 24rpx 0 0;

		.pop-item {
			padding: 32rpx 0;
			border-bottom: 2rpx solid #F2F2F2;

			&:last-of-type {
				border-bottom: 16rpx solid #F2F2F2;
			}
		}

		.pop-cancel-item {
			background-color: #FFFFFF;
			padding: 32rpx 0;
			margin-top: 16rpx;
		}
	}
}
</style>

